package com.qc.jpush;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.qc.entity.OrderEntity;
import com.qc.entity.OrderScheduleEntity;
import com.qc.entity.UserEntity;
import com.qc.entity.message.ChatMessageEntity;
import com.qc.serverlistener.CacheUtil;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import net.sf.json.JSONObject;

/**
 * 进行推送的关键在于构建一个 PushPayload 对象。
 * JPush精确分为：alias(别名)，tag，registrationID 三种类型进行精确推送
 * 还有推送所有，推送安卓用户，推送iOS用户。可以自己参数
 * @author wyw
 *
 */
public class JPushUtil {

	protected static final String APP_KEY ="d090b5024e01a7180957247b";
    protected static final String MASTER_SECRET = "8cf71ff17fa5fc1ca6edbb77";
	
	public static final String TITLE = "Test from API example";
    public static final String ALERT = "测试推送";
    public static final String MSG_CONTENT = "Test from API Example - msgContent";
    public static final String REGISTRATION_ID = "1517bfd3f7cb7f93a82";
    public static final String TAG = "tag_api";
    
    public static final boolean IS_PRODUCTION = false;//推送环境，true/生产  false/开发
    
    //wyw
    public static final String sound = "happy";

	public static void main(String[] args) {

		ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        
        // For push, all you need do is to build PushPayload object.
//        PushPayload payload = buildPushObject_all_all_alert();
        PushEntity entity = new PushEntity();
        entity.pushContent = ALERT;
        entity.pushType = 1;
        entity.pushValue = "";
        entity.registrationId = "1517bfd3f7cb7f93a82";
        PushPayload payload = buildPushObject_all_RegID_alert(entity);
        
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println("Got result - " + result);
            
        } catch (APIConnectionException e) {
            
        } catch (APIRequestException e) {
        	System.out.println("HTTP Status: " + e.getStatus());
        	System.out.println("Error Code: " + e.getErrorCode());
        	System.out.println("Error Message: " + e.getErrorMessage());
        	System.out.println("Msg ID: " + e.getMsgId());
        }
	}
	
	/**
	 * 聊天推送
	 */
	public static void chatPush(ChatMessageEntity entity) {
		UserEntity cachUserInfo = CacheUtil.getUserInfo(entity.getTargetId());
		//发送推送
		String content = entity.getContent();
		if (entity.getContentType() == 1) {
			content = "图片消息";
		}
		PushEntity push = new PushEntity();
		push.pushType = 1;
		push.pushContent = entity.getSenderNickname() + ":" + content;
		push.pushValue = JSONObject.fromObject(entity).toString();
		push.registrationId = cachUserInfo.getRegistrationId();
		
		JPushUtil.defaultPush(push);
	}
	
	/**
	 * 订单行程消息推送
	 * @param entity
	 */
	public static void orderMessage(OrderScheduleEntity entity,long bossId) {
        UserEntity cachUserInfo = CacheUtil.getUserInfo(bossId);
        //发送推送
        String content = "新的行程将于:" + entity.getShortTime() + " 开始，点击查看详情";
        PushEntity push = new PushEntity();
        push.pushType = 2;
        push.pushContent = content;
        push.pushValue = JSONObject.fromObject(entity).toString();
        push.registrationId = cachUserInfo.getRegistrationId();
        
        JPushUtil.defaultPush(push);
    }
	
	/**
	 * app 红点推送
	 * @param type ( 3/最近来访推送, 4/我的粉丝增加推送, 5/我接到的聘单推送, 6/职业认证状态改变 7/系统通知推送)
	 */
	public static void redDotPush(int type, long userId,String content) {
		UserEntity cachUserInfo = CacheUtil.getUserInfo(userId);
		PushEntity push = new PushEntity();
        push.pushType = type;
        push.pushContent = content;
        push.registrationId = cachUserInfo.getRegistrationId();
        
        JPushUtil.defaultPush(push);
	}
	
	/**
	 * 调用推送
	 * @param type
	 */
	public static void defaultPush(PushEntity push) {
		if (push.registrationId != null && !push.registrationId.equals("")) {
            PushPayload payload = buildPushObject_all_RegID_alert(push);

            ClientConfig clientConfig = ClientConfig.getInstance();
            JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
            try {
                PushResult result = jpushClient.sendPush(payload);
                System.out.println("JPush result - " + result);
                
            } catch (APIConnectionException e) {
                
            } catch (APIRequestException e) {
                System.out.println("HTTP Status: " + e.getStatus());
                System.out.println("Error Code: " + e.getErrorCode());
                System.out.println("Error Message: " + e.getErrorMessage());
                System.out.println("Msg ID: " + e.getMsgId());
            }
        }
	}
	
	/**
	 * 根据REGISTRATION_ID推送
	 * @return
	 */
	public static PushPayload buildPushObject_all_RegID_alert(PushEntity push) {
		Map<String, String> extras = new HashMap<>();
		extras.put("pushType", push.pushType+"");
		extras.put("pushValue", push.pushValue);
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.registrationId(push.registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(push.pushContent)
                                .setBadge(1)
                                .setSound(sound)
                                .addExtras(extras)
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(IS_PRODUCTION).build())
                .build();
    }
	
	/**
	 * 快捷地构建推送对象：所有平台，所有设备，内容为 ALERT 的通知。
	 * @return
	 */
	public static PushPayload buildPushObject_all_all_alert() {
	    return PushPayload.alertAll(ALERT);
	}
	
	/**
	 * 构建推送对象：所有平台，推送目标是别名为 "alias1"，通知内容为 ALERT。
	 * @return
	 */
    public static PushPayload buildPushObject_all_alias_alert() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias("alias1"))
                .setNotification(Notification.alert(ALERT))
                .setOptions(Options.newBuilder().setApnsProduction(IS_PRODUCTION).build())
                .build();
    }
    
    /**
     * 构建推送对象：平台是 Android，目标是 tag 为 "tag1" 的设备，内容是 Android 通知 ALERT，并且标题为 TITLE。
     * @return
     */
    public static PushPayload buildPushObject_android_tag_alertWithTitle() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.android(ALERT, TITLE, null))
                .setOptions(Options.newBuilder().setApnsProduction(IS_PRODUCTION).build())
                .build();
    }
    
    public static PushPayload buildPushObject_android_and_ios() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.newBuilder()
                		.setAlert("alert content")
                		.addPlatformNotification(AndroidNotification.newBuilder()
                				.setTitle("Android Title").build())
                		.addPlatformNotification(IosNotification.newBuilder()
                				.incrBadge(1)
                				.addExtra("extra_key", "extra_value").build())
                		.build())
                .setOptions(Options.newBuilder().setApnsProduction(IS_PRODUCTION).build())
                .build();
    }

    public static void buildPushObject_with_extra() {

        JsonObject jsonExtra = new JsonObject();
        jsonExtra.addProperty("extra1", 1);
        jsonExtra.addProperty("extra2", false);

        Map<String, String> extras = new HashMap<String, String>();
        extras.put("extra_1", "val1");
        extras.put("extra_2", "val2");

        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.newBuilder()
                        .setAlert("alert content")
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle("Android Title")
                                .addExtras(extras)
                                .addExtra("booleanExtra", false)
                                .addExtra("numberExtra", 1)
                                .addExtra("jsonExtra", jsonExtra)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .addExtra("extra_key", "extra_value").build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(IS_PRODUCTION).build())
                .build();

        System.out.println(payload.toJSON());
    }
    
    /**
     * 构建推送对象：平台是 iOS，推送目标是 "tag1", "tag_all" 的交集，推送内容同时包括通知与消息 - 通知信息是 ALERT，角标数字为 5，
     * 通知声音为 "happy"，并且附加字段 from = "JPush"；消息内容是 MSG_CONTENT。通知是 APNs 推送通道的，消息是 JPush 应用内消息通道的。
     * APNs 的推送环境是“生产”（如果不显式设置的话，Library 会默认指定为开发）
     * @return
     */
    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(ALERT)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                 .setMessage(Message.content(MSG_CONTENT))
                 .setOptions(Options.newBuilder()
                         .setApnsProduction(true)
                         .build())
                 .build();
    }

    public static PushPayload buildPushObject_android_newly_support() {
        JsonObject inbox = new JsonObject();
        inbox.add("line1", new JsonPrimitive("line1 string"));
        inbox.add("line2", new JsonPrimitive("line2 string"));
        inbox.add("contentTitle", new JsonPrimitive("title string"));
        inbox.add("summaryText", new JsonPrimitive("+3 more"));
        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(ALERT)
                        .setBigPicPath("path to big picture")
                        .setBigText("long text")
                        .setBuilderId(1)
                        .setCategory("CATEGORY_SOCIAL")
                        .setInbox(inbox)
                        .setStyle(1)
                        .setTitle("Alert test")
                        .setPriority(1)
                        .build())
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.registrationId("1517bfd3f7cb7f93a82"))
                .setNotification(notification)
                .setOptions(Options.sendno())
                .build();
    }
    
    /**
     * 构建推送对象：平台是 Andorid 与 iOS，推送目标是 （"tag1" 与 "tag2" 的并集）交（"alias1" 与 "alias2" 的并集），
     * 推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush。
     * @return
     */
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(IS_PRODUCTION).build())
                .build();
    }
}
